<?php
/**
*
* @package phpBB3 stockvirtual
* @version $Id$
* @copyright (c) 2005 phpBB Group, 2011 Minway Hsu
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
*/

/**
* @ignore
*/
if (!defined('IN_PHPBB'))
{
	exit;
}

// get the latest trading date on which ALL user values are calculated completely (so a running calculation will not be considered). 
function get_latest_date_for_ranking()
{
	global	$db;	
	
	$date = '';	
	
	$sql = 'SELECT MAX(begin_time) from sv_service_task WHERE task="update_all_user_value"';
	$result = $db->sql_query($sql); 
	if ($row = $db->sql_fetchrow($result))
	{		
		$date = get_latest_trading_date($row['MAX(begin_time)']);		
	}
	else
	{
		// fall back to get a latest date 
		$sql = 'SELECT MAX( date ) FROM sv_user_value';	
		$result = $db->sql_query($sql); 
		if ($row = $db->sql_fetchrow($result))
		{
			$date = $row['date'];
		}
	}
	
	$db->sql_freeresult($result);
	
	return $date;
}

function list_user_roi_ranking($period = 30, $list = 'roi_1_month_list',$max = 20, $user_id = 0, $fb_friends = '', $list_to_user_id = 0, $only_fb_user = false)
{
	global	$db, $template;
	
	$show = false;
	
	// exclude users not visiting for 3 months
	$now = get_taiwan_time();
	$limit = $now - LOGIN_WITHIN_DAYS_FOR_RANKING * 24 * 60 *60;
	
	if ($fb_friends == '')
	{
		$sql	= "SELECT user_id, roi FROM sv_user_roi WHERE period = $period AND user_id IN ( SELECT user_id FROM phpbb_users WHERE user_lastvisit > $limit ) ORDER BY roi DESC";
		
		// If we only FB users, don't set limit in SQL queries.
		if ($only_fb_user)
			$result = $db->sql_query($sql); 
		else
			$result = $db->sql_query_limit($sql, $max); 
		$i = 1;
		while ($row = $db->sql_fetchrow($result))
		{	
			if ($only_fb_user && get_user_fb_id($row['user_id']) == 0)
				continue;
				
			// Send vars to template
			$template->assign_block_vars($list, array(
				'INDEX'							=> $i,
				'USER_ID'						=> $row['user_id'],
				'USER_NAME'						=> get_username($row['user_id']),
				'USER_FB_ID'					=> get_user_fb_id($row['user_id']),
				'ROI'							=> round($row['roi']*100, 1),
				)
			);
			++$i;
			$show = true;
			
			if ($list_to_user_id != 0 && $list_to_user_id == $row['user_id'])
			{
				break;
			}
			if ($only_fb_user && $i > $max)
			{
				break;
			}
		}
	}
	else
	{	
		$sql	= "SELECT user_id, roi FROM sv_user_roi WHERE (user_id=$user_id OR user_id IN ($fb_friends)) AND period = $period ORDER BY roi DESC";
		$result = $db->sql_query_limit($sql, $max); 
		$i = 1;
		while ($row = $db->sql_fetchrow($result))
		{	
			// Send vars to template
			$template->assign_block_vars($list, array(
				'INDEX'							=> $i,
				'USER_ID'						=> $row['user_id'],
				'USER_NAME'						=> get_username($row['user_id']),
				'USER_FB_ID'					=> get_user_fb_id($row['user_id']),
				'ROI'							=> round($row['roi']*100, 1),
				)
			);
			++$i;
			$show = true;
		}
	}
	
	$db->sql_freeresult($result);
	
	return $show;
}

// max: max records to show.
// user_id: the current user id. Only used in FB friends ranking page.
// fb_friends: a strings contains all FB friends. Only used in FB friends ranking page.
// list_to_user_id: list all records until the current user. 
function list_user_value_ranking($max = 30, $user_id = 0, $fb_friends = '', $list_to_user_id = 0, $only_fb_user = false)
{
	global	$db, $template, $date;	// $date is used to pass the date back 
	
	$show = false;

	// exclude users not visiting for 3 months
	$now = get_taiwan_time();
	$limit = $now - LOGIN_WITHIN_DAYS_FOR_RANKING * 24 * 60 *60;
	
	// get the latest trading date on which ALL user values are calculated completely (so a running calculation will not be considered). 
	$date = get_latest_date_for_ranking();	
		
	// On normal ranking page.
	if ($fb_friends == '')
	{
		// list highest 30 user values in the latest date. 
		$sql	= "SELECT user_id, value, money, date FROM sv_user_value WHERE date =$date  AND user_id IN ( SELECT user_id FROM phpbb_users WHERE user_lastvisit > $limit ) ORDER BY value DESC";
		
		// If we only FB users, don't set limit in SQL queries.
		if ($only_fb_user)
			$result = $db->sql_query($sql); 
		else
			$result = $db->sql_query_limit($sql, $max); 
		$i = 1;
		while ($row = $db->sql_fetchrow($result))
		{
			if ($only_fb_user && get_user_fb_id($row['user_id']) == 0)
				continue;
				
			// Send vars to template
			$template->assign_block_vars('list', array(
				'INDEX'							=> $i,
				'USER_ID'						=> $row['user_id'],
				'USER_NAME'						=> get_username($row['user_id']),
				'USER_FB_ID'					=> get_user_fb_id($row['user_id']),
				'VALUE'							=> number_format($row['value']),
				'MONEY'							=> number_format($row['money']),
				)
			);
			++$i;
			$show = true;
			
			if ($list_to_user_id != 0 && $list_to_user_id == $row['user_id'])
			{
				break;
			}
			if ($only_fb_user && $i > $max)
			{
				break;
			}
		}
	}
	// on FB friends ranking page.
	else
	{
		$sql	= "SELECT * FROM `sv_user_value` WHERE (user_id=$user_id OR user_id IN ($fb_friends)) AND date =$date ORDER BY value DESC";
		$result = $db->sql_query_limit($sql, $max); 
		$i = 1;
		while ($row = $db->sql_fetchrow($result))
		{	
			// Send vars to template
			$template->assign_block_vars('list', array(
				'INDEX'							=> $i,
				'USER_ID'						=> $row['user_id'],
				'USER_NAME'						=> get_username($row['user_id']),
				'USER_FB_ID'					=> get_user_fb_id($row['user_id']),
				'VALUE'							=> number_format($row['value']),
				'MONEY'							=> number_format($row['money']),
				)
			);
			++$i;
		
			$show = true;
		}
	}

	$db->sql_freeresult($result);
	
	return $show;
}

// list user value ranking in full list.
// starting_ranking: start from this ranking number
// max: max number returned
// only_fb_user: no for normal page, yes for FB page
function list_user_value_full_ranking($starting_ranking, $max = 20, $only_fb_user = false)
{
	global	$db, $template, $date;
	
	$show = false;

	// exclude users not visiting for 3 months
	$now = get_taiwan_time();
	$limit = $now - LOGIN_WITHIN_DAYS_FOR_RANKING * 24 * 60 *60;
	
	// On normal ranking page.
	
	// list highest 30 user values in the latest date. 
	$sql	= "SELECT user_id, value, money, date FROM sv_user_value WHERE date = (SELECT MAX( date ) FROM sv_user_value ) AND user_id IN ( SELECT user_id FROM phpbb_users WHERE user_lastvisit > $limit ) ORDER BY value DESC";
		
	// If we only FB users, don't set limit in SQL queries.
	if ($only_fb_user)
		$result = $db->sql_query($sql); 
	else
		$result = $db->sql_query_limit($sql, $starting_ranking + $max); 
	
	$i 			= 0;
	$ranking 	= 1;
	while ($row = $db->sql_fetchrow($result))
	{
		if ($only_fb_user && get_user_fb_id($row['user_id']) == 0)
			continue;
				
		if ($ranking < $starting_ranking)
		{
			++ $ranking;
			continue;
		}			
		
		// get user roi		
		$have_roi_30 = $have_roi_90 = $have_roi_180 = $have_roi_360 = $have_roi_720 = $have_roi_1080 = $have_roi_1440 = false;
		$sql2	= 'SELECT period, roi FROM sv_user_roi WHERE period IN (30, 90, 180, 360, 720, 1080, 1440) AND user_id=' . $row['user_id'] ;
		$result2 = $db->sql_query_limit($sql2, 7);
		while ($row2 = $db->sql_fetchrow($result2))
		{
			if ($row2['period'] == '30')
			{
				$roi_30 = $row2['roi'];
				$have_roi_30 = true;
				if (abs($roi_30) < 0.01)
					$roi_30 = 0;
			}
			if ($row2['period'] == '90')
			{
				$roi_90 = $row2['roi'];
				$have_roi_90 = true;
				if (abs($roi_90) < 0.01)
					$roi_90 = 0;
			}
			if ($row2['period'] == '180')
			{
				$roi_180 = $row2['roi'];
				$have_roi_180 = true;
				if (abs($roi_180) < 0.01)
					$roi_180 = 0;
			}
			if ($row2['period'] == '360')
			{
				$roi_360 = $row2['roi'];
				$have_roi_360 = true;
				if (abs($roi_360) < 0.01)
					$roi_360 = 0;
			}						
			if ($row2['period'] == '720')
			{
				$roi_720 = $row2['roi'];
				$have_roi_720 = true;
				if (abs($roi_720) < 0.01)
					$roi_720 = 0;
			}			
			if ($row2['period'] == '1080')
			{
				$roi_1080 = $row2['roi'];
				$have_roi_1080 = true;
				if (abs($roi_1080) < 0.01)
					$roi_1080 = 0;
			}			
			if ($row2['period'] == '1440')
			{
				$roi_1440 = $row2['roi'];
				$have_roi_1440 = true;
				if (abs($roi_1440) < 0.01)
					$roi_1440 = 0;
			}			
		}
		
		// Send vars to template
		$template->assign_block_vars('list', array(
				'INDEX'							=> $i + $starting_ranking,
				'USER_ID'						=> $row['user_id'],
				'USER_NAME'						=> get_username($row['user_id']),
				'USER_FB_ID'					=> get_user_fb_id($row['user_id']),
				'VALUE'							=> number_format($row['value']),
				'MONEY'							=> number_format($row['money']),
				'ROI_30'						=> round($roi_30 * 100, 1),
				'ROI_90'						=> round($roi_90 * 100, 1),
				'ROI_180'						=> round($roi_180 * 100, 1),
				'ROI_360'						=> round($roi_360 * 100, 1),
				'ROI_720'						=> round($roi_720 * 100, 1),
				'ROI_1080'						=> round($roi_1080 * 100, 1),
				'ROI_1440'						=> round($roi_1440 * 100, 1),
				'HAVE_ROI_30'					=> $have_roi_30,
				'HAVE_ROI_90'					=> $have_roi_90,
				'HAVE_ROI_180'					=> $have_roi_180,
				'HAVE_ROI_360'					=> $have_roi_360,
				'HAVE_ROI_720'					=> $have_roi_720,
				'HAVE_ROI_1080'					=> $have_roi_1080,
				'HAVE_ROI_1440'					=> $have_roi_1440,
				)
		);
		++$i;
		$show = true;
		$date = $row['date'];
			
		if ($list_to_user_id != 0 && $list_to_user_id == $row['user_id'])
		{
			break;
		}
		if ($i >= $max)
		{
			break;
		}
	}

	$db->sql_freeresult($result);
	
	return $i;	
}

// list user ROI ranking in full list.
// period: can be 30, 90, 180, 360
// starting_ranking: start from this ranking number
// max: max number returned
// only_fb_user: no for normal page, yes for FB page
function list_user_roi_full_ranking($period, $starting_ranking, $max = 20, $only_fb_user = false)
{
	global	$db, $template, $date;
	
	$show = false;

	// exclude users not visiting for 3 months
	$now = get_taiwan_time();
	$limit = $now - LOGIN_WITHIN_DAYS_FOR_RANKING * 24 * 60 *60;
	
	// On normal ranking page.
	
	// list highest 30 user values in the latest date. 
//	$sql	= "SELECT user_id, value, money, date FROM sv_user_value WHERE date = (SELECT MAX( date ) FROM sv_user_value ) AND user_id IN ( SELECT user_id FROM phpbb_users WHERE user_lastvisit > $limit ) ORDER BY value DESC";		
	$sql	= "SELECT * FROM sv_user_roi WHERE period = $period AND user_id IN ( SELECT user_id FROM phpbb_users WHERE user_lastvisit > $limit ) ORDER BY roi DESC";
		
	// If we only FB users, don't set limit in SQL queries.
	if ($only_fb_user)
		$result = $db->sql_query($sql); 
	else
		$result = $db->sql_query_limit($sql, $starting_ranking + $max); 
	
	$i 			= 0;
	$ranking 	= 1;
	while ($row = $db->sql_fetchrow($result))
	{
		if ($only_fb_user && get_user_fb_id($row['user_id']) == 0)
			continue;
				
		if ($ranking < $starting_ranking)
		{
			++ $ranking;
			continue;
		}			
		
		// get user value. 
		$sql2	= 'SELECT user_id, value, money FROM sv_user_value WHERE user_id=' . $row['user_id'] . ' ORDER BY date DESC';		
		$result2 = $db->sql_query_limit($sql2, 1);
		if ($row2 = $db->sql_fetchrow($result2))
		{
			$value = $row2['value'];
			$money = $row2['money'];
			
		}
		else
		{
			continue;
		}
		
		// get user roi
		$have_roi_30 = $have_roi_90 = $have_roi_180 = $have_roi_360 = $have_roi_720 = $have_roi_1080 = $have_roi_1440 = false;
		$sql2	= 'SELECT period, roi FROM sv_user_roi WHERE period IN (30, 90, 180, 360, 720, 1080, 1440) AND user_id=' . $row['user_id'] ;
		$result2 = $db->sql_query_limit($sql2, 7);
		while ($row2 = $db->sql_fetchrow($result2))
		{
			if ($row2['period'] == '30')
			{
				$roi_30 = $row2['roi'];
				$have_roi_30 = true;
				if (abs($roi_30) < 0.01)
					$roi_30 = 0;
			}
			if ($row2['period'] == '90')
			{
				$roi_90 = $row2['roi'];
				$have_roi_90 = true;
				if (abs($roi_90) < 0.01)
					$roi_90 = 0;
			}
			if ($row2['period'] == '180')
			{
				$roi_180 = $row2['roi'];
				$have_roi_180 = true;
				if (abs($roi_180) < 0.01)
					$roi_180 = 0;
			}
			if ($row2['period'] == '360')
			{
				$roi_360 = $row2['roi'];
				$have_roi_360 = true;
				if (abs($roi_360) < 0.01)
					$roi_360 = 0;
			}			
			if ($row2['period'] == '720')
			{
				$roi_720 = $row2['roi'];
				$have_roi_720 = true;
				if (abs($roi_720) < 0.01)
					$roi_720 = 0;
			}			
			if ($row2['period'] == '1080')
			{
				$roi_1080 = $row2['roi'];
				$have_roi_1080 = true;
				if (abs($roi_1080) < 0.01)
					$roi_1080 = 0;
			}			
			if ($row2['period'] == '1440')
			{
				$roi_1440 = $row2['roi'];
				$have_roi_1440 = true;
				if (abs($roi_1440) < 0.01)
					$roi_1440 = 0;
			}			
		}
		
		// Send vars to template
		$template->assign_block_vars('list', array(
				'INDEX'							=> $i + $starting_ranking,
				'USER_ID'						=> $row['user_id'],
				'USER_NAME'						=> get_username($row['user_id']),
				'USER_FB_ID'					=> get_user_fb_id($row['user_id']),
				'VALUE'							=> number_format($value),
				'MONEY'							=> number_format($money),
				'ROI_30'						=> round($roi_30 * 100, 1),
				'ROI_90'						=> round($roi_90 * 100, 1),
				'ROI_180'						=> round($roi_180 * 100, 1),
				'ROI_360'						=> round($roi_360 * 100, 1),
				'ROI_720'						=> round($roi_720 * 100, 1),
				'ROI_1080'						=> round($roi_1080 * 100, 1),
				'ROI_1440'						=> round($roi_1440 * 100, 1),
				'HAVE_ROI_30'					=> $have_roi_30,
				'HAVE_ROI_90'					=> $have_roi_90,
				'HAVE_ROI_180'					=> $have_roi_180,
				'HAVE_ROI_360'					=> $have_roi_360,
				'HAVE_ROI_720'					=> $have_roi_720,
				'HAVE_ROI_1080'					=> $have_roi_1080,
				'HAVE_ROI_1440'					=> $have_roi_1440,
				)
		);
		++$i;
		$show = true;
		$date = $row['date'];
		
		$db->sql_freeresult($result2);
		
		if ($i >= $max)
		{
			break;
		}
	}

	$db->sql_freeresult($result);
	
	return $i;	
}

//
// list the users followed by the current user (followee) 
//
function list_following_user($user_id)
{
	global	$db, $template;
	
	$show = false;	
		
	// list highest 30 user values in the latest date. 
	$sql	= "SELECT user_id, value, money FROM sv_user_value WHERE date = (SELECT MAX( date ) FROM sv_user_value ) AND user_id IN ( SELECT followee_user_id FROM sv_follow_list WHERE follower_user_id = $user_id ) ORDER BY value DESC";
	$result = $db->sql_query($sql); 
	
	$i 			= 1;
	
	while ($row = $db->sql_fetchrow($result))
	{		
		// get user roi
		$have_roi_30 = $have_roi_90 = $have_roi_180 = $have_roi_360 = false;
		$sql2	= 'SELECT period, roi FROM sv_user_roi WHERE period IN (30, 90, 180, 360) AND user_id=' . $row['user_id'] ;
		$result2 = $db->sql_query_limit($sql2, 4);
		while ($row2 = $db->sql_fetchrow($result2))
		{
			if ($row2['period'] == '30')
			{
				$roi_30 = $row2['roi'];
				$have_roi_30 = true;
				if (abs($roi_30) < 0.01)
					$roi_30 = 0;
			}
			if ($row2['period'] == '90')
			{
				$roi_90 = $row2['roi'];
				$have_roi_90 = true;
				if (abs($roi_90) < 0.01)
					$roi_90 = 0;
			}
			if ($row2['period'] == '180')
			{
				$roi_180 = $row2['roi'];
				$have_roi_180 = true;
				if (abs($roi_180) < 0.01)
					$roi_180 = 0;
			}
			if ($row2['period'] == '360')
			{
				$roi_360 = $row2['roi'];
				$have_roi_360 = true;
				if (abs($roi_360) < 0.01)
					$roi_360 = 0;
			}			
		}
		
		// Send vars to template
		$template->assign_block_vars('followee_list', array(
				'INDEX'							=> $i,
				'USER_ID'						=> $row['user_id'],
				'USER_NAME'						=> get_username($row['user_id']),
				'USER_FB_ID'					=> get_user_fb_id($row['user_id']),
				'VALUE'							=> number_format($row['value']),
				'MONEY'							=> number_format($row['money']),
				'ROI_30'						=> round($roi_30 * 100, 1),
				'ROI_90'						=> round($roi_90 * 100, 1),
				'ROI_180'						=> round($roi_180 * 100, 1),
				'ROI_360'						=> round($roi_360 * 100, 1),
				'HAVE_ROI_30'					=> $have_roi_30,
				'HAVE_ROI_90'					=> $have_roi_90,
				'HAVE_ROI_180'					=> $have_roi_180,
				'HAVE_ROI_360'					=> $have_roi_360,
				)
		);
		++$i;
		$show = true;
		$date = $row['date'];
	
		$db->sql_freeresult($result2);	
	}

	$db->sql_freeresult($result);
	
	return $i;	
}



function include_nav_links()
{
	global $template, $phpbb_root_path, $phpEx, $in_fb_iframe,$user_id;
	
	$is_following_anyone = is_following_anyone($user_id);
	
	// Assign index specific vars
	if ($in_fb_iframe)
	{
		$template->assign_vars(array(
			'S_SV_INDEX'					=> append_sid("{$phpbb_root_path}fb/index.$phpEx", ''),
			'S_BUY_ACTION'					=> append_sid("{$phpbb_root_path}fb/buy.$phpEx", ''),
			'S_SELL_ACTION'					=> append_sid("{$phpbb_root_path}fb/sell.$phpEx", ''),
			'S_PERFORMANCE_ACTION'			=> append_sid("{$phpbb_root_path}fb/performance.$phpEx", ''),
			'S_RANKING_ACTION'				=> append_sid("{$phpbb_root_path}fb/ranking.$phpEx", ''),
			'S_RULE'						=> append_sid("{$phpbb_root_path}fb/rule.$phpEx", ''),
			'S_ABOUT'						=> append_sid("{$phpbb_root_path}fb/sv_about.$phpEx", ''),
			'S_FAQ'							=> append_sid("{$phpbb_root_path}fb/sv_faq.$phpEx", ''),
			'S_FOLLOW_INFO'					=> append_sid("{$phpbb_root_path}fb/follow_info.$phpEx", ''),
			
			'IS_FOLLOWING_ANYONE'			=>	$is_following_anyone,
		));
	}
	else
	{
		$template->assign_vars(array(
			'S_SV_INDEX'					=> append_sid("{$phpbb_root_path}index.$phpEx", ''),
			'S_BUY_ACTION'					=> append_sid("{$phpbb_root_path}buy.$phpEx", ''),
			'S_SELL_ACTION'					=> append_sid("{$phpbb_root_path}sell.$phpEx", ''),
			'S_PERFORMANCE_ACTION'			=> append_sid("{$phpbb_root_path}performance.$phpEx", ''),
			'S_RANKING_ACTION'				=> append_sid("{$phpbb_root_path}ranking.$phpEx", ''),
			'S_RULE'						=> append_sid("{$phpbb_root_path}rule.$phpEx", ''),
			'S_ABOUT'						=> append_sid("{$phpbb_root_path}sv_about.$phpEx", ''),
			'S_FAQ'							=> append_sid("{$phpbb_root_path}sv_faq.$phpEx", ''),
			'S_FOLLOW_INFO'					=> append_sid("{$phpbb_root_path}follow_info.$phpEx", ''),
			
			'IS_FOLLOWING_ANYONE'			=>	$is_following_anyone,
		));
	}
	
}

// list recent related equity change events.
function list_equity_change_event($query_user_id)
{
	global	$db, $equity_change_event_list, $template;
		
	$equity_change_event_list = false;
	$today = get_date_from_time(get_taiwan_time());
	
	$sql 	= 'SELECT * FROM sv_holding_stock WHERE user_id=' . $query_user_id;
	$result = $db->sql_query($sql); 
	while ($row = $db->sql_fetchrow($result))
	{
		$corp_id = $row['corp_id'];
		
		$sql2		= 'SELECT * FROM sv_equity_change_event WHERE corp_id="' . $corp_id . '" AND status="new"';
		$result2	= $db->sql_query($sql2); 
		while ($row2 = $db->sql_fetchrow($result2))
		{
			// check if the scheduled date is passed. If so, just skip.			
			$scheduled_date 		= $row2['scheduled_date'];
			if (strcmp($today, $scheduled_date) > 0)
				continue;
						
			$equity_change_event_list = true;
			
			$share_unit				= $row2['share_unit'];
			$cash_after_change 		= $row2['cash_after_change'];
			$corp_id_after_change 	= $row2['corp_id_after_change'];
			$share_after_change 	= $row2['share_after_change'];
			$corp_id_after_change_2 = $row2['corp_id_after_change_2'];
			$share_after_change_2 	= $row2['share_after_change_2'];
			$corp_id_after_change_3 = $row2['corp_id_after_change_3'];
			$share_after_change_3 	= $row2['share_after_change_3'];
			
			$execution_date 		= $row2['execution_date'];

			// we should display the share unit as TRANSACTION_UNIT, 1000. 
			if ($share_unit != TRANSACTION_UNIT)
			{
				$m = $share_unit / TRANSACTION_UNIT;			
				$share_unit 			/= $m;	
				$cash_after_change		/= $m;
				$share_after_change		/= $m;
				$share_after_change_2 	/= $m;
				$share_after_change_3 	/= $m;
			}
			
			// Send vars to template
			$template->assign_block_vars('equity_change_event_list', array(		
				'CORP_ID'							=> $corp_id,
				'CORP_NAME'							=> get_corp_chinese_name($corp_id),
				'SHARE_UNIT'						=> $share_unit,		
				'DIVIDEND_CASH'						=> round($cash_after_change / $share_unit, 2),
				'DIVIDEND_SHARE'					=> round(($share_after_change - $share_unit) / $share_unit, 2),
				'CASH_AFTER_CHANGE'					=> $cash_after_change,
				'CORP_ID_AFTER_CHANGE'				=> $corp_id_after_change,
				'CORP_NAME_AFTER_CHANGE'			=> get_corp_chinese_name($corp_id_after_change),
				'SHARE_AFTER_CHANGE' 				=> $share_after_change,
				'CORP_ID_AFTER_CHANGE_2'			=> $corp_id_after_change_2,
				'CORP_NAME_AFTER_CHANGE_2'			=> get_corp_chinese_name($corp_id_after_change_2),
				'SHARE_AFTER_CHANGE_2' 				=> $share_after_change_2,
				'CORP_ID_AFTER_CHANGE_3'			=> $corp_id_after_change_3,
				'CORP_NAME_AFTER_CHANGE_3'			=> get_corp_chinese_name($corp_id_after_change_3),
				'SHARE_AFTER_CHANGE_3' 				=> $share_after_change_3,
				'SCHEDULED_DATE' 					=> get_date_string($scheduled_date),				
				)
			);		
		}
		
		$db->sql_freeresult($result2);
	}	
	
	$db->sql_freeresult($result);
	
	$template->assign_vars(array(
			'S_EQUITY_CHANGE_EVENT_LIST'			=> $equity_change_event_list,
			'TWSE_YEAR'								=> get_year_from_date(get_date_from_time(get_taiwan_time())),
			'TWSE_MONTH'							=> get_month_from_date(get_date_from_time(get_taiwan_time())),
		));
}


// list all open to_buy delegation. 
function list_open_to_buy_delegation()
{
	global	$db, $to_buy_delegation_list, $template, $user_id;
	
	$sql 	= 'SELECT * FROM sv_transaction WHERE user_id=' . $user_id . ' AND action="to_buy"';
	$result = $db->sql_query($sql); 
	while ($row = $db->sql_fetchrow($result))
	{
		if (is_valid_corp_id($row['corp_id']) == false)
		{
			continue;
		}
		
		$to_buy_delegation_list = true;
	
		$check_time = 0;
		if ((int)$row['check_time'] != 0)
		{
			$check_time = get_time_string((int)$row['check_time']);
		}
	
		// Send vars to template
		$template->assign_block_vars('to_buy_delegation_list', array(		
			'TRANS_ID'						=> $row['transaction_id'],
			'CORP_ID'						=> $row['corp_id'],
			'CORP_NAME'						=> get_corp_chinese_name($row['corp_id']),
			'NUMBER'						=> (int)$row['share'] / TRANSACTION_UNIT,			
			'REQUEST_PRICE'					=> $row['request_price'],
			'NOTE'							=> utf8_normalize_nfc($row['note']),
			'CHECK_TIME'					=> $check_time,
			'CHECK_STATUS'					=> $row['check_status'],
			)
		);
	}
	
	$db->sql_freeresult($result);
}

// list all open to_sell delegation. 
function list_open_to_sell_delegation($off_hour_sell = false)
{
	global	$db, $to_sell_delegation_list, $template, $user_id;
	
	if ($off_hour_sell)
		$sql 	= 'SELECT * FROM sv_transaction WHERE user_id=' . $user_id . ' AND action="to_sell_off_hour"';
	else
		$sql 	= 'SELECT * FROM sv_transaction WHERE user_id=' . $user_id . ' AND action="to_sell"';
	$result = $db->sql_query($sql); 
	while ($row = $db->sql_fetchrow($result))
	{
		if (is_valid_corp_id($row['corp_id']) == false)
		{
			continue;
		}
		
		$to_sell_delegation_list = true;
	
		$check_time = 0;
		if ((int)$row['check_time'] != 0)
		{
			$check_time = get_time_string((int)$row['check_time']);
		}
		
		if ($off_hour_sell)
			$number = (int)$row['share'];	
		else
			$number = (int)((int)$row['share'] / TRANSACTION_UNIT);
		
		// Send vars to template
		$template->assign_block_vars('to_sell_delegation_list', array(
			'TRANS_ID'						=> $row['transaction_id'],
			'CORP_ID'						=> $row['corp_id'],
			'CORP_NAME'						=> get_corp_chinese_name($row['corp_id']),
			'NUMBER'						=> $number, 
			'REQUEST_PRICE'					=> $row['request_price'],
			'NOTE'							=> utf8_normalize_nfc($row['note']),
			'CHECK_TIME'					=> $check_time,
			'CHECK_STATUS'					=> $row['check_status'],
			)
		);
	}
	
	$db->sql_freeresult($result);
}


// list all open to_short_sell delegation. 
function list_open_to_short_sell_delegation()
{
	global	$db, $to_short_sell_delegation_list, $template, $user_id;
	
	$sql 	= 'SELECT * FROM sv_transaction WHERE user_id=' . $user_id . ' AND action="to_short_sell"';
	$result = $db->sql_query($sql); 
	while ($row = $db->sql_fetchrow($result))
	{
		if (is_valid_corp_id($row['corp_id']) == false)
		{
			continue;
		}
		
		$to_short_sell_delegation_list = true;
	
		$check_time = 0;
		if ((int)$row['check_time'] != 0)
		{
			$check_time = get_time_string((int)$row['check_time']);
		}
	
		// Send vars to template
		$template->assign_block_vars('to_short_sell_delegation_list', array(		
			'TRANS_ID'						=> $row['transaction_id'],
			'CORP_ID'						=> $row['corp_id'],
			'CORP_NAME'						=> get_corp_chinese_name($row['corp_id']),
			'NUMBER'						=> (int)$row['share'] / TRANSACTION_UNIT,	
			'REQUEST_PRICE'					=> $row['request_price'],		
			'NOTE'							=> utf8_normalize_nfc($row['note']),
			'CHECK_TIME'					=> $check_time,
			'CHECK_STATUS'					=> $row['check_status'],
			)
		);
	}
	
	$db->sql_freeresult($result);
}

// list all open to_sell delegation. 
function list_open_to_short_cover_delegation()
{
	global	$db, $to_short_cover_delegation_list, $template, $user_id;
	
	$sql 	= 'SELECT * FROM sv_transaction WHERE user_id=' . $user_id . ' AND action="to_short_cover"';
	$result = $db->sql_query($sql); 
	while ($row = $db->sql_fetchrow($result))
	{
		if (is_valid_corp_id($row['corp_id']) == false)
		{
			continue;
		}
		
		$to_short_cover_delegation_list = true;
	
		$check_time = 0;
		if ((int)$row['check_time'] != 0)
		{
			$check_time = get_time_string((int)$row['check_time']);
		}
		
		// Send vars to template
		$template->assign_block_vars('to_short_cover_delegation_list', array(
			'TRANS_ID'						=> $row['transaction_id'],
			'CORP_ID'						=> $row['corp_id'],
			'CORP_NAME'						=> get_corp_chinese_name($row['corp_id']),
			'NUMBER'						=> (int)$row['share'] / TRANSACTION_UNIT,	
			'REQUEST_PRICE'					=> $row['request_price'],		
			'NOTE'							=> utf8_normalize_nfc($row['note']),
			'CHECK_TIME'					=> $check_time,
			'CHECK_STATUS'					=> $row['check_status'],
			)
		);
	}
	
	$db->sql_freeresult($result);
}

// list delegations
function list_delegation($user_id, $show_note, $all_user = false, $period = 0, $only_fb_user = false)
{
	global	$db, $template;
	
	$list = false;
	
	// get personal setting
	$result = get_personal_setting();
	if (isset($result))
	{
		$delegation_list_info_option	= $result['delegation_list_info'];
	}
	else
	{
		$delegation_list_info_option	= 0;	// default as basic info
	}
	
	$template->assign_vars(array(
					'DELEGATION_LIST_INFO_OPTION'				=> $delegation_list_info_option,
				));
	
	// handle the query user page and performance page.
	if ($all_user == false)
	{		
		// limited action types with basic info
		if ($delegation_list_info_option == 0)
			$sql 	= 'SELECT * FROM sv_transaction WHERE user_id=' . $user_id . ' AND (action=\'buy\' OR action=\'sell\' OR action=\'short_sell\' OR action=\'short_cover\' OR action=\'forced_short_cover_equity\' OR action=\'forced_short_cover_maintenance\' OR action=\'forced_short_cover\') ORDER BY request_time DESC';
		else
			$sql 	= 'SELECT * FROM sv_transaction WHERE user_id=' . $user_id . ' ORDER BY request_time DESC';
			
		$result = $db->sql_query_limit($sql, 500); 
		while ($row = $db->sql_fetchrow($result))
		{
			if (is_valid_corp_id($row['corp_id']) == false)
			{
				continue;
			}
	
			$list = true;
	
			$deal_time = 0;
			if ((int)$row['deal_time'] != 0)
			{
				$deal_time = get_time_string((int)$row['deal_time']);
			}
			$check_time = 0;
			if ((int)$row['check_time'] != 0)
			{
				$check_time = get_time_string((int)$row['check_time']);
			}
			
			// Send vars to template
			$template->assign_block_vars('list', array(		
					'CORP_ID'						=> $row['corp_id'],
					'CORP_NAME'						=> get_corp_chinese_name($row['corp_id']),
					'NUMBER'						=> (int)$row['share'] / TRANSACTION_UNIT,
					'ACTION'						=> $row['action'],
					'REQUEST_TIME'					=> get_time_string((int)$row['request_time']),
					'PRICE'							=> $row['price'],
					'REQUEST_PRICE'					=> $row['request_price'],
					'TOTAL_AMOUNT'					=> number_format(round($row['price'] * $row['share'], 0)),
					'TRANSACTION_TAX'				=> number_format(round($row['price'] * $row['share'] * SECURITY_TRANSACTION_TAX, 0)),
					'DEAL_TIME'						=> $deal_time,
					'NOTE'							=> $row['note'],
					'CHECK_TIME'					=> $check_time,
					'CHECK_STATUS'					=> $row['check_status'],
					)
			);
			
			if ($show_note)
			{	
				$template->assign_vars(array(
					'SHOW_NOTE'				=> true,
				));
			}
			
		}		
		
		$db->sql_freeresult($result);
		
		return $list;
	}
	
	$template->assign_vars(array(
					'SHOW_ALL_USER_DELEGATION'				=> true,
				));
				
	$request_time = get_taiwan_time() - $period*24*60*60;
	
	if ($only_fb_user)
	{
		// limited action types with basic info
		if ($delegation_list_info_option == 0)
			$sql 	= 'SELECT * FROM sv_transaction WHERE user_id IN ( SELECT user_id FROM phpbb_facebook_user) AND request_time>' . $request_time . ' AND (action=\'buy\' OR action=\'sell\' OR action=\'short_sell\' OR action=\'short_cover\') ORDER BY request_time DESC';
		else
			$sql 	= 'SELECT * FROM sv_transaction WHERE user_id IN ( SELECT user_id FROM phpbb_facebook_user) AND request_time>' . $request_time . ' ORDER BY request_time DESC';
	}
	else	
	{
		// limited action types with basic info
		if ($delegation_list_info_option == 0)
			$sql 	= 'SELECT * FROM sv_transaction WHERE request_time>' . $request_time . ' AND (action=\'buy\' OR action=\'sell\' OR action=\'short_sell\' OR action=\'short_cover\') ORDER BY request_time DESC';
		else
			$sql 	= 'SELECT * FROM sv_transaction WHERE request_time>' . $request_time . ' ORDER BY request_time DESC';
	}		
			
	$result = $db->sql_query_limit($sql, 500); 
	while ($row = $db->sql_fetchrow($result))
	{
		if (is_valid_corp_id($row['corp_id']) == false)
		{
			continue;
		}
	
		$list = true;
	
		$deal_time = 0;
		if ((int)$row['deal_time'] != 0)
		{
			$deal_time = get_time_string((int)$row['deal_time']);
		}
		$check_time = 0;
		if ((int)$row['check_time'] != 0)
		{
			$check_time = get_time_string((int)$row['check_time']);
		}
		
		// Send vars to template
		$template->assign_block_vars('list', array(
			'USER_ID'						=> $row['user_id'],
			'USER_FB_ID'					=> get_user_fb_id($row['user_id']),
			'USERNAME'						=> get_username($row['user_id']),
			'CORP_ID'						=> $row['corp_id'],
			'CORP_NAME'						=> get_corp_chinese_name($row['corp_id']),
			'NUMBER'						=> (int)$row['share'] / TRANSACTION_UNIT,
			'ACTION'						=> $row['action'],
			'REQUEST_TIME'					=> get_time_string((int)$row['request_time']),
			'PRICE'							=> $row['price'],
			'REQUEST_PRICE'					=> $row['request_price'],
			'TOTAL_AMOUNT'					=> number_format(round($row['price'] * $row['share'], 0)),
			'TRANSACTION_TAX'				=> number_format(round($row['price'] * $row['share'] * SECURITY_TRANSACTION_TAX, 0)),
			'DEAL_TIME'						=> $deal_time,
			'NOTE'							=> $row['note'],
			'CHECK_TIME'					=> $check_time,
			'CHECK_STATUS'					=> $row['check_status'],
			)
		);
	}
	
	$db->sql_freeresult($result);
	
	return $list;	
}


// list all holding stock.
function list_holding_stock($query_user_id = '', $show_stock_max = 0, $detail_url = '', $allow_edit_note = false, $allow_edit_stop_loss_profit = false, $use_FLASH = true)
{
	global	$db,$template, $user_id;
	
	if ($query_user_id == '')
	{
		$query_user_id = $user_id;
	}
	
	if ($allow_edit_note)
	{
		// list his own sotck and allow to edit notes. 
		$template->assign_vars(array(
			'S_SHOW_NOTE_IN_ASSET_LIST'				=> true,
			'S_USER_ID'								=> $user_id,
		));
	}
	if ($allow_edit_stop_loss_profit)
	{
		// list his own sotck and allow to edit notes. 
		$template->assign_vars(array(
			'S_ALLOW_EDIT_STOP_LOSS_PROFIT'				=> true,
		));
		
	}
	
	$holding_any_stock		= false;
	$shorting_any_stock		= false;
	$not_all_stock_showed 	= false;
	
	// get the user money.
	$sql	= 'SELECT * FROM phpbb_users WHERE user_id=' . $query_user_id;
	$result	= $db->sql_query_limit($sql, 1);
	$row	= $db->sql_fetchrow($result);
	$money 	= $row['user_money'];			
	$value 	= 0;
	
	$pie_value 				= array();
	$pie_value_html5		= array();
	$pie_label_html5		= array();
	
	$holding_stock_array	= array();
	$shorting_stock_array	= array();
		
	// calculate total market value.
	$total_market_value = 0;
	
	$sql 	= 'SELECT * FROM sv_holding_stock WHERE user_id=' . $query_user_id;
	$result = $db->sql_query($sql); 
	while ($row = $db->sql_fetchrow($result))
	{
		$refered_price	 		= get_refered_price($row['corp_id']);
		$market_value 			= $refered_price * $row['share'];
		$total_market_value		+= $market_value;
		
		$holding_any_stock		= true;
		
		// save for later use
		$holding_stock_array[]	= $row;
	}
	
	$db->sql_freeresult($result);
	
	// calculate all deposit and gain/loss from short stock
	$total_gain_or_loss	= 0;
	$total_deposit		= 0;
	
	$sql 	= 'SELECT * FROM sv_short_stock WHERE user_id=' . $query_user_id;
	$result = $db->sql_query($sql); 
	while ($row = $db->sql_fetchrow($result))
	{
		$refered_price	 		= get_refered_price($row['corp_id']);
		$cost					= $row['cost'];
		$deposit				= $row['deposit'];
		$share					= $row['share'];
		$gain_or_loss			= ($cost - $refered_price)* $row['share'];

		$total_gain_or_loss		+= $gain_or_loss;
		$total_deposit			+= $deposit;
		
		// save for later use
		$shorting_stock_array[]	= $row;		
	}
	
	$db->sql_freeresult($result);
	
	$value = $money + $total_market_value + $total_gain_or_loss + $total_deposit;
		
	$template->assign_vars(array(
			'TOTAL_VALUE_IN_HOLDING_STOCK_LIST'				=> number_format($value),
			'MONEY_IN_HOLDING_STOCK_LIST'					=> number_format($money),
			'VALUE_IN_HOLDING_STOCK_LIST'					=> number_format($total_market_value),
			'SHORT_IN_HOLDING_STOCK_LIST'					=> number_format($total_deposit + $total_gain_or_loss),
			'DEPOSIT_IN_HOLDING_STOCK_LIST'					=> number_format($total_deposit),			
			'GAIN_OR_LOSS_IN_HOLDING_STOCK_LIST'			=> number_format($total_gain_or_loss),
			'MAINTENANCE_RATE'								=> round(cal_maintenance_rate($total_deposit, $total_gain_or_loss), 0),
		));
	
	// Assign index specific vars
	if ($value != 0)
	{		
		$per	= round($money*100/$value, 0);
		$name 	= ' ' . "現金 " . $per . '%';
		
		if ($use_FLASH)
		{
			$tmp = new pie_value($per, $name);			
			$tmp->set_label($name, '#454545', 12 );
			$pie_value[] = $tmp;		
		}
		else
		{
			$pie_value_html5[] = $per;
			$pie_label_html5[] = $name;
		}
	
		$template->assign_vars(array(
			'MONEY_PERCENTAGE_IN_HOLDING_STOCK_LIST'		=> round($money*100/$value, 1),
			'VALUE_PERCENTAGE_IN_HOLDING_STOCK_LIST'		=> round(($total_market_value)*100/$value, 1),
			'SHORT_PERCENTAGE_IN_HOLDING_STOCK_LIST'		=> round(($total_deposit + $total_gain_or_loss)*100/$value, 1),
		));
	}
		
	// list all holding stocks.		
	$i = 1;	
	foreach ($holding_stock_array as $row)
	{
		if (is_valid_corp_id($row['corp_id']) == false)
		{
			continue;
		}
		
		$holding_stock_list = true;
		
		$refered_price	 		= get_refered_price($row['corp_id']);
		$cost 					= (float)$row['cost'];
		$note 					= $row['note'];
		$stop_loss 				= (float)$row['stop_loss'];
		$stop_profit			= (float)$row['stop_profit'];
		$market_value 			= $refered_price * $row['share'];
		$market_value_percent	= '';
		if ($value != 0)
		{
			$market_value_percent = round($market_value * 100 / $value, 0);
		}
		$difference_price_percent = '';
		if ($cost != 0)
		{
			$difference_price_percent = round(($refered_price - $cost)*100/$cost, 1);
		}
		
		$stop_loss_reached 		= false;
		$stop_profit_reached 	= false;
		
		if ($stop_loss != 0 && $cost * (1 - $stop_loss) > $refered_price)
		{
			$stop_loss_reached = true;						
		}				
		if ($stop_profit != 0 && $cost * (1 + $stop_profit) < $refered_price)
		{
			$stop_profit_reached = true;						
		}
		
		// Check if we exceed the max stock number.
		if ($show_stock_max != 0 && $i > $show_stock_max)
		{
			$not_all_stock_showed = true;			
		}
		else
		{
			// Send vars to template
			$template->assign_block_vars('holding_stock_list', array(
				'CORP_ID'						=> $row['corp_id'],
				'CORP_NAME'						=> get_corp_chinese_name($row['corp_id']),
				'NUMBER'						=> (int)$row['share'] / TRANSACTION_UNIT,
				'COST'							=> round($cost, 1),
				'STOP_LOSS'						=> round($stop_loss, 1),
				'STOP_PROFIT'					=> round($stop_profit, 1),
				'STOP_LOSS_IN_PERCENT'			=> round($stop_loss * 100, 0),
				'STOP_PROFIT_IN_PERCENT'		=> round($stop_profit * 100, 0),
				'STOP_LOSS_REACHED'				=> $stop_loss_reached,
				'STOP_PROFIT_REACHED'			=> $stop_profit_reached,
				'REFERED_PRICE'					=> $refered_price,
				'DIFFERENCE_PRICE'				=> round($refered_price - $cost, 1),
				'DIFFERENCE_PRICE_PERCENT'		=> $difference_price_percent,
				'MARKET_VALUE'					=> number_format(round($market_value, 0)),
				'MARKET_VALUE_PERCENT'			=> $market_value_percent,
				'NOTE'							=> $note,
				
				)
			);		
		}		
		
		// don't show the stock less than 1% on pie chart.
		$per	= round($market_value * 100 / $value, 0);
		
		if ($per != 0)
		{
			// Add pie value to pie chart.			
			$name 	= ' ' . get_corp_chinese_name($row['corp_id']) . '(' . $row['corp_id'] . ') ' . $per . '%';
			
			if ($use_FLASH)
			{
				$tmp = new pie_value($per, $name);			
				$tmp->set_label($name, '#454545', 12 );
				$pie_value[] = $tmp;		
			}
			else
			{
				$pie_value_html5[] = $per;
				$pie_label_html5[] = $name;
			}			
		}
		
		$i += 1;
		
		
	}
	
	$template->assign_vars(array(
			'NOT_ALL_STOCK_SHOWED'					=> $not_all_stock_showed,
			'HOLDING_STOCK_DETAIL_URL'				=> $detail_url,
			));
			
	// list all short stocks.		
	$i = 1;	
	foreach ($shorting_stock_array as $row)
	{
		if (is_valid_corp_id($row['corp_id']) == false)
		{
			continue;
		}
		
		$short_stock_list 	= true;
		$shorting_any_stock = true;
		
		$refered_price	 		= get_refered_price($row['corp_id']);
		$cost 					= (float)$row['cost'];
		$stop_loss 				= (float)$row['stop_loss'];
		$stop_profit			= (float)$row['stop_profit'];
		$note 					= $row['note'];
		$deposit 				= $row['deposit'];
		$market_value 			= $refered_price * $row['share'];
		$gain_or_loss			= ($cost - $refered_price) * $row['share'];
		
		$difference_price_percent = '';
		if ($cost != 0)
		{
			$difference_price_percent = round(($refered_price - $cost)*100/$cost, 1);
		}
		
		$stop_loss_reached 		= false;
		$stop_profit_reached 	= false;
		
		if ($stop_loss != 0 && $cost * (1 + $stop_loss) < $refered_price)
		{
			$stop_loss_reached = true;						
		}				
		if ($stop_profit != 0 && $cost * (1 - $stop_profit) > $refered_price)
		{
			$stop_profit_reached = true;						
		}
		
		// Check if we exceed the max stock number.
		if ($show_stock_max != 0 && $i > $show_stock_max)
		{
			$not_all_stock_showed = true;			
		}
		else
		{
			// Send vars to template
			$template->assign_block_vars('short_stock_list', array(
				'CORP_ID'						=> $row['corp_id'],
				'CORP_NAME'						=> get_corp_chinese_name($row['corp_id']),
				'NUMBER'						=> (int)$row['share'] / TRANSACTION_UNIT,
				'COST'							=> round($cost, 1),
				'STOP_LOSS'						=> round($stop_loss, 1),
				'STOP_PROFIT'					=> round($stop_profit, 1),
				'STOP_LOSS_IN_PERCENT'			=> round($stop_loss * 100, 0),
				'STOP_PROFIT_IN_PERCENT'		=> round($stop_profit * 100, 0),
				'STOP_LOSS_REACHED'				=> $stop_loss_reached,
				'STOP_PROFIT_REACHED'			=> $stop_profit_reached,
				'REFERED_PRICE'					=> $refered_price,
				'DIFFERENCE_PRICE'				=> round($refered_price - $cost, 1),
				'DIFFERENCE_PRICE_PERCENT'		=> $difference_price_percent,
				'DEPOSIT'						=> number_format($deposit),
				'GAIN_OR_LOSS'					=> number_format($gain_or_loss),
				'NOTE'							=> $note,
				)
			);		
		}
		
		$i += 1;		
	}
	
	// add short part to the pie chart.
	if ($total_deposit != 0)
	{
		$per	= round(($total_deposit + $total_gain_or_loss) * 100 / $value, 0);
		$name 	= ' 融券部位 ' . $per . '%';
		
		if ($use_FLASH)
		{
			$tmp = new pie_value($per, $name);			
			$tmp->set_label($name, '#454545', 12 );
			$pie_value[] = $tmp;		
		}
		else
		{
			$pie_value_html5[] = $per;
			$pie_label_html5[] = $name;
		}
			
	}
	
	if ($value != 0 && $use_FLASH)
	{
		// draw the pie chart.
		$title = new title( '' );	
	
		$pie = new pie();
		$pie->set_start_angle( 0 );
		$pie->set_animate( true );
//		$pie->set_tooltip( '#label# #percent# ' );
		$pie->set_tooltip( '#label# ' );
		$pie->set_values($pie_value);
//		$pie->set_colours( array( '#FF0000', '#FF8000', '#8F8F00', '#00BF00','#0080FF', '#0000FF','#8000FF','#454545') );
//		$pie->set_colours( array( '#74AAC6', '#7E7367', '#BD665B', '#E88896','#B0CABB', '#EB996C','#B8C853','#F85546', '#EED307') );
//		$pie->set_colours( array( '#649AB6', '#6E6357', '#AD564B', '#D87886','#A0BAAB', '#DB895C','#A8B843','#E84536', '#DEC307') );
		$pie->set_colours( array( '#548AA6', '#5E5347', '#9D463B', '#C86876','#90AA9B', '#CB794C','#98A833','#D83526', '#CEB307') );
	
		$chart = new open_flash_chart();
		$chart->set_title( $title );
		$chart->add_element( $pie );

		$chart->x_axis = null;

		$chart->set_bg_colour('#ECF1F3');
		
		$holding_stock_jason_string = $chart->toPrettyString();	
	
		$template->assign_vars(array(
			'HOLDING_STOCK_JASON_STRING'					=> $holding_stock_jason_string,
			));
	}
	else if ($value != 0 && $use_FLASH == false)	
	{		
		$value_percent_str 		= implode(",", $pie_value_html5);
		$value_label_str 		= implode("','", $pie_label_html5);
		
		$template->assign_vars(array(
			'HOLDING_STOCK_VALUE_PERCENT_HTML5'					=> $value_percent_str,
			'HOLDING_STOCK_VALUE_LABEL_HTML5'					=> $value_label_str,
			));
	}
	
	
	

	$template->assign_vars(array(			
		'S_HOLDING_STOCK_LIST'		=> $holding_stock_list,
		'S_SHORT_STOCK_LIST'		=> $short_stock_list,		
	));
	
	$r = array();
	$r['shorting_any_stock'] 	= $shorting_any_stock;
	$r['holding_any_stock'] 	= $holding_any_stock;
	
	return $r;
}

// use open flash chart to draw user values.
function draw_user_value_html5($user_id)
{
	global $db, $performance, $jason_string, $template;
	
	
	// get the total number of records	
	$sql 	= 'SELECT COUNT(*) FROM sv_user_value WHERE user_id=' . $user_id . ' ORDER BY date ASC';
	$result = $db->sql_query($sql); 
	$r		= $db->sql_fetchrow($result);
	$num 	= $r['COUNT(*)'];
	
	$db->sql_freeresult($result);
	
	// steps on X label.
	// control the horizontal grid number to be 15, since the vertical grid number is 10.
	$steps	= (int)($num/15) + 1;

	// get user value
	$sql 	= 'SELECT * FROM sv_user_value WHERE user_id=' . $user_id . ' ORDER BY date ASC';
	$result = $db->sql_query($sql); 
	$date	= array();
	$value	= array();
	$taiex	= array();
	$max	= 0;
	$min	= 100000000000; // just pick a number big enough for now. 
	$num	= 0;
	
	$initial		= 0;
	$taiex_initial	= 0;
	
	$taiex_max	= 0;
	$taiex_min	= 200000;

	$old_year	= '';
	
	while ($row = $db->sql_fetchrow($result))
	{
		$performance = true;
	
		if ($num % $steps == 0 && $old_year != get_year_from_date($row['date']))
		{
			$date[] 	= get_date_string($row['date']);
			$old_year	= get_year_from_date($row['date']);
		}
		else
		{
			$date[] 	= ' ' . get_month_from_date($row['date']) . '.' . get_day_from_date($row['date']);
		}
		
		$value[]	= (int)$row['value'];		
	
		if ($max < (int)$row['value'])
			$max = (int)$row['value'];
		if ($min > (int)$row['value'])
			$min = (int)$row['value'];
		
		// In some case(like Chinese New Year, the user valuss are calculated but the TAIEX is not updated.
		// We use the TAIEX of the previous day for simple handling.
		$index = get_taiex($row['date']);
		if ($index != '')
			$taiex_index	= (int)($index);
		
		$taiex[]		= $taiex_index;
		if ($taiex_max < $taiex_index)
			$taiex_max = $taiex_index;
		if ($taiex_min > $taiex_index)
			$taiex_min = $taiex_index;		
		
		// save the initial value
		if ($taiex_initial == 0)
			$taiex_initial 	= $taiex_index;
		if ($initial == 0)
			$initial 	= (int)$row['value'];
		
		++$num;
	}
	
	$db->sql_freeresult($result);
	
	$user_value_str 		= implode(",", $value);
	$user_value_tooltip_str	= implode("','", $value);
	$taiex_str 				= implode(",", $taiex);
	$date_str 				= implode(",", $date);
	
	$template->assign_vars(array(			
		'S_USER_VALUE_HTML5'				=> $user_value_str,
		'S_USER_VALUE_TOOLTIP_HTML5'		=> $user_value_tooltip_str,
		'S_TAIEX_HTML5'						=> $taiex_str,
		'S_DATE_HTML5'						=> $date_str,
		
	));
}

// use open flash chart to draw user values.
function draw_user_value($user_id)
{
	global $db, $performance, $jason_string;
	
	// get the total number of records	
	$sql 	= 'SELECT COUNT(*) FROM sv_user_value WHERE user_id=' . $user_id . ' ORDER BY date ASC';
	$result = $db->sql_query($sql); 
	$r		= $db->sql_fetchrow($result);
	$num 	= $r['COUNT(*)'];
	
	$db->sql_freeresult($result);
	
	// steps on X label.
	// control the horizontal grid number to be 15, since the vertical grid number is 10.
	$steps	= (int)($num/15) + 1;

	// get user value
	$sql 	= 'SELECT * FROM sv_user_value WHERE user_id=' . $user_id . ' ORDER BY date ASC';
	$result = $db->sql_query($sql); 
	$date	= array();
	$value	= array();
	$taiex	= array();
	$max	= 0;
	$min	= 100000000000; // just pick a number big enough for now. 
	$num	= 0;
	
	$initial		= 0;
	$taiex_initial	= 0;
	
	$taiex_max	= 0;
	$taiex_min	= 200000;

	$old_year	= '';
	
	while ($row = $db->sql_fetchrow($result))
	{
		$performance = true;
	
		if ($num % $steps == 0 && $old_year != get_year_from_date($row['date']))
		{
			$date[] 	= get_date_string($row['date']);
			$old_year	= get_year_from_date($row['date']);
		}
		else
		{
			$date[] 	= ' ' . get_month_from_date($row['date']) . '.' . get_day_from_date($row['date']);
		}
		
		$value[]	= (int)$row['value'];		
	
		if ($max < (int)$row['value'])
			$max = (int)$row['value'];
		if ($min > (int)$row['value'])
			$min = (int)$row['value'];
		
		// In some case(like Chinese New Year, the user valuss are calculated but the TAIEX is not updated.
		// We use the TAIEX of the previous day for simple handling.
		$index = get_taiex($row['date']);
		if ($index != '')
			$taiex_index	= (int)($index);
		
		$taiex[]		= $taiex_index;
		if ($taiex_max < $taiex_index)
			$taiex_max = $taiex_index;
		if ($taiex_min > $taiex_index)
			$taiex_min = $taiex_index;		
		
		// save the initial value
		if ($taiex_initial == 0)
			$taiex_initial 	= $taiex_index;
		if ($initial == 0)
			$initial 	= (int)$row['value'];
		
		++$num;
	}
	
	$db->sql_freeresult($result);
	
	//
	// 	Calculate max/min/grid for Y-axis 
	//
	//	The max, min and grid are calculated so that user total asset values and TAIEX are in correct proportiona, and the overall chart is clear.
	//	
	
	//echo "taiex_max:$taiex_max, taiex_min:$taiex_min <BR>" . PHP_EOL;

	// First, we calculate the max up/down percentage for user value.	
	$up_percent 	= abs($max - $initial) / $initial;
	$down_percent 	= abs($initial - $min) / $initial;
	//echo "up_percent:$up_percent, down_percent:$down_percent <BR>" . PHP_EOL;
	
	// Second, we calculate the max up/down percentage for TAIEX during the period. 
	$taiex_up_percent 		= abs($taiex_max - $taiex_initial) / $taiex_initial;
	$taiex_down_percent 	= abs($taiex_initial - $taiex_min) / $taiex_initial;
	//echo "taiex_up_percent:$taiex_up_percent, taiex_down_percent:$taiex_down_percent <BR>" . PHP_EOL;
	
	// Third, we can have the max up/down percentage for both user value and TAIEX during the period. 
	$up				= max($up_percent, $taiex_up_percent);
	$down			= max($down_percent, $taiex_down_percent);
	$major_change	= max($up, $down);	
	//echo "up:$up, down:$down, major_change:$major_change <BR>" . PHP_EOL;
	
	// The vertical grid number is set to 10.
	$grid_num		= 10;
	
	// We assign grids to 'up' and 'down' sides. Make sure that at least 1 grid is reserved for each side. 
	// The major change referes to the side with higher changes. 
	$grid_for_major_change = floor($major_change * $grid_num / ($up + $down));
	
	if ($grid_for_major_change == $grid_num)
		$grid_for_major_change = $grid_num - 1;
	
	$grid_for_minor_change = $grid_num - $grid_for_major_change;
	//echo "grid_for_major_change:$grid_for_major_change,  grid_for_minor_change:$grid_for_minor_change <BR>" . PHP_EOL;
	
	$mapping_ratio = $grid_for_major_change / $major_change;
	
	if ($up == $major_change)
	{
		$down 			= $grid_for_minor_change / $mapping_ratio;
		$grids_above	= $grid_for_major_change;
		$grids_below	= $grid_for_minor_change;
	}
	else
	{
		$up = $grid_for_minor_change / $mapping_ratio;
		$grids_above	= $grid_for_minor_change;		
		$grids_below	= $grid_for_major_change;
	}
	//echo "up:$up, down:$down, major_change:$major_change <BR>" . PHP_EOL;
	
	
	// the initial user value 
	$original			= 10000000;				
	// the basic unit for the max/min of user value is 1,000,000 
	$basic_unit 		= 1000000;
	
	
	
	$max	= ceil($initial * (1 + $up) / $basic_unit) * $basic_unit;
	$min	= floor($initial * (1- $down) / $basic_unit) * $basic_unit;	
	$grid 	= ($max - $min) / $grid_num;	
	//echo "max:$max, min:$min grid:$grid<BR>" . PHP_EOL;
	
	
	// Calculate the max, min for the chart of user value and TAIEX. 
	$chart_max = $original + $grids_above * $grid;
	$chart_min = $original - $grids_below * $grid;
	//echo "chart_max:$chart_max, chart_min:$chart_min<BR>" . PHP_EOL;
	
	$taiex_max = ceil($taiex_initial * (1 + abs($chart_max - $initial) / $initial));
	$taiex_min = floor($taiex_initial * (1 - abs($chart_min - $initial) / $initial));
	//echo "taiex_max:$taiex_max, taiex_min:$taiex_min<BR>" . PHP_EOL; 
	
	
	
	// prepare open-flash-chart 
	$chart = new open_flash_chart();

	$title = new title('');
	$chart->set_title( $title );
	
	
	$def = new dot();
	$def->size(3)->tooltip('#x_label#<br>市值:#val#');
	
	$line = new line();
	$line->set_colour( '#5B56B6' );
	$line->set_values( $value );
	$line->set_key( '', $num );
	$line->set_default_dot_style( $def );	
	$chart->add_element( $line );
	
	$taiex_dot = new dot();
	$taiex_dot->size(3)->tooltip('#x_label#<br>加權指數:#val#');
	
	$taiex_line	= new line();
	$taiex_line->set_colour( '#BFAFAF');
	$taiex_line->set_values( $taiex );	
	$taiex_line->set_key( '', $num );
	$taiex_line->set_default_dot_style( $taiex_dot );		
	$taiex_line->attach_to_right_y_axis();
	$chart->add_element( $taiex_line );
	
	$x_labels = new x_axis_labels();
	$x_labels->set_steps( $steps );
	$x_labels->set_vertical();
	$x_labels->set_colour( '#A2ACBA' );
	$x_labels->set_labels( $date );
	
	$x = new x_axis();
	$x->set_colour( '#424242' );
	$x->set_grid_colour( '#D7E4A3' );
	$x->set_offset( false );
	$x->set_steps($steps);
	// Add the X Axis Labels to the X Axis
	$x->set_labels( $x_labels ); 
	
	$chart->set_x_axis( $x );
	
	$y = new y_axis();
	$y->set_colour( '#5B56B6' );
	$y->set_range( $chart_min, $chart_max, ($chart_max- $chart_min)/10 ); //min, max, interval
	$chart->set_y_axis( $y );
	
	$y_right = new y_axis_right();
	$y_right->set_range( $taiex_min, $taiex_max, (int)(($taiex_max - $taiex_min)/10));
	$y_right->set_stroke( 3 );
	$y_right->set_colour( '#BFAFAF' );
	$y_right->set_tick_length( 12 );
	$y_right->set_steps( (int)(($taiex_max - $taiex_min)/10));
	$chart->set_y_axis_right( $y_right );
		
	$jason_string = $chart->toPrettyString();	
}

// list knowledge title on index pages

function list_knowledge_titles()
{
	global $db, $template;
	
	$show_knowledge = false;
	
	if (is_knowledge_db_ok())
	{
		$titles = get_knowledge_titles();

		if (sizeof($titles) > 0)
		{
			$show_knowledge = true;
		
			foreach($titles as $id => $title)
			{
				$template->assign_block_vars('knowledge_titles', array(
					'ID'							=> $id,
					'TITLE'							=> $title,
					)
				);
			}	
		}
	}
	
	return $show_knowledge;
}

// list a poll.
function list_poll()
{
	global $db, $template, $user_id, $user, $phpbb_root_path, $phpEx;
	
	// get a poll which this user didn't vote
	$voted_topic = array();
	$sql 	= 'SELECT DISTINCT topic_id FROM ' . POLL_VOTES_TABLE . '
				WHERE vote_user_id = ' . $user_id ;
	$result = $db->sql_query($sql);
	while ($row = $db->sql_fetchrow($result))
	{
		$voted_topic[] = $row['topic_id'];
	}	

	$voted_topic = implode(',', $voted_topic);
	
//	print '<br> voted_topic <br>';
//	print $voted_topic . ' <br>';

	$options 			= array();
	$possible_topics	= array();
	
	if ($voted_topic != '')
	{
		$sql	= 'SELECT * FROM ' . POLL_OPTIONS_TABLE . 
				" WHERE topic_id NOT IN ($voted_topic)";				
	}
	else
	{
		$sql	= 'SELECT * FROM ' . POLL_OPTIONS_TABLE . 	
				" ORDER BY topic_id AND poll_option_id";
	}
	
	$result = $db->sql_query($sql);
	while ($row	= $db->sql_fetchrow($result))
	{
		$options[] 							= $row;
		$possible_topics[$row['topic_id']]	= $row['topic_id'];	
	}
	
	$db->sql_freeresult($result);
	
//	print '<br> possible_topics <br>';
//	print_r($possible_topics);

	$valid = false;
	
	foreach ($possible_topics as $topic_id)
	{
		// check if the poll is valid (with a correct topic type and correct forum)		
		$sql2 = 'SELECT * FROM ' . TOPICS_TABLE . ' WHERE topic_id=' . $topic_id;
		$result2 = $db->sql_query_limit($sql2, 1);
		if ($row2 = $db->sql_fetchrow($result2))
		{
			$topic_type = $row2['topic_type'];	
			$forum_id = $row2['forum_id'];
			
			// get the forum
			$sql3 = 'SELECT * FROM ' . FORUMS_TABLE . ' WHERE forum_id=' . $forum_id;
			$result3 = $db->sql_query_limit($sql3, 1);
			if ($row3 = $db->sql_fetchrow($result3))
			{
				$parent_id = $row3['parent_id'];
				
				if ($topic_type == POST_ANNOUNCE && $parent_id == 0)
				{
					// check if the poll is closed.
					$poll_start = $row2['poll_start'];	
					$poll_length = $row2['poll_length'];	
					
					if ($poll_length == 0 || time() < $poll_length + $poll_start)
					{
						$valid 		= true;
						$topic_data = $row2;
					}
				}
			}
		}
		
		// Break once we have find a valid topic(poll).
		if ($valid)
			break;
	}
	
//	print '<br> valid: <br>';
//	print $valid . ' topic: ' . $topic_id . ' ' . $topic_info['poll_title'];
	
	// A valid poll is found.
	if ($valid == false)
		return;
		
	
	// Get all the options of the selected topic.
	$poll_info = array();
	foreach ($options as $option)
	{
		if ($option['topic_id'] == $topic_id)
			$poll_info[] = $option;	
	}
	
	// calculate total votes
	$poll_total = 0;
	foreach ($poll_info as $poll_option)
	{
		$poll_total += $poll_option['poll_option_total'];
	}
		
	// generate vote key.
	$vote_key = md5(' ' . $user_id . 'vote_key' . $topic_id);	
	
	// list poll info
	$s_can_vote			= true;
	$s_display_results 	= true;
		
	foreach ($poll_info as $poll_option)
	{
		$option_pct = ($poll_total > 0) ? $poll_option['poll_option_total'] / $poll_total : 0;
		$option_pct_txt = sprintf("%.1d%%", round($option_pct * 100));
	
		$template->assign_block_vars('poll_option', array(
			'POLL_OPTION_ID' 		=> $poll_option['poll_option_id'],
			'POLL_OPTION_CAPTION' 	=> $poll_option['poll_option_text'],
			'POLL_OPTION_RESULT' 	=> $poll_option['poll_option_total'],
			'POLL_OPTION_PERCENT' 	=> $option_pct_txt,
			'POLL_OPTION_PCT'		=> round($option_pct * 100),
			'POLL_OPTION_IMG' 		=> $user->img('poll_center', $option_pct_txt, round($option_pct * 250)),
			'POLL_OPTION_VOTED'		=> false,
			)
		);
	}
	
	$poll_end = $topic_data['poll_length'] + $topic_data['poll_start'];
//	$viewtopic_url = append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id&amp;start=$start" . ((strlen($u_sort_param)) ? "&amp;$u_sort_param" : '') . (($highlight_match) ? "&amp;hilit=$highlight" : ''));
	
	$template->assign_vars(array(
		'POLL_QUESTION'		=> $topic_data['poll_title'],
		'TOTAL_VOTES' 		=> $poll_total,
		'POLL_LEFT_CAP_IMG'	=> $user->img('poll_left'),
		'POLL_RIGHT_CAP_IMG'=> $user->img('poll_right'),
	
		'L_MAX_VOTES'		=> ($topic_data['poll_max_options'] == 1) ? $user->lang['MAX_OPTION_SELECT'] : sprintf($user->lang['MAX_OPTIONS_SELECT'], $topic_data['poll_max_options']),
		'L_POLL_LENGTH'		=> ($topic_data['poll_length']) ? sprintf($user->lang[($poll_end > time()) ? 'POLL_RUN_TILL' : 'POLL_ENDED_AT'], $user->format_date($poll_end)) : '',
	
		'S_HAS_POLL'		=> true,
		'S_CAN_VOTE'		=> $s_can_vote,
		'S_DISPLAY_RESULTS'	=> $s_display_results,
		'S_IS_MULTI_CHOICE'	=> ($topic_data['poll_max_options'] > 1) ? true : false,
		'S_POLL_ACTION'		=> $viewtopic_url,
	
		'U_VIEW_RESULTS'	=> $viewtopic_url . '&amp;view=viewpoll',
		
		'S_VOTE_KEY'		=> $vote_key,
		'S_USER_ID'			=> $user_id,
		'S_VOTE_TOPIC_ID'	=> $topic_id,
		)
	);	
	
}


// list news.
function list_news($user_id, $max = 10)
{
	global $db, $template;
	
	$corp = get_user_interested_corp($user_id, 10);
	
	if (sizeof($corp) == 0)
		return;
	
	$corp_str = "'" . implode("', '",$corp) . "'";
	
	$show_news 		= false;
	$i				= 0;
	$corp_count		= array();
	$news_listed	= array();
	
	// Output this info to page for tracking.
	$template->assign_vars(array(
					'INTERESTED_CORP_LIST'				=> $corp_str,
				));
				
	// only shows news after this time 
	$sql	= 'SELECT * FROM phpbb_users WHERE user_id=' . $user_id . ' ';
	$result = $db->sql_query_limit($sql, 1);	
	if ($thisrow = $db->sql_fetchrow($result))
	{		
		$news_after_this_time 	= $thisrow['user_lastvisit'];
	}
	else
	{
		$news_after_this_time 	= get_taiwan_time() - 3 * 24 * 60 * 60;
	}

				
				
	// get related news. 
	$sql 	= "SELECT * FROM sv_news WHERE corp_id IN ( $corp_str ) AND time > $news_after_this_time ORDER BY time DESC";
	$result = $db->sql_query_limit($sql, $max * 2);
	while ($row = $db->sql_fetchrow($result))
	{
		$news_id	= $row['news_id'];
		$corp_id	= $row['corp_id'];
		
		// check if the user have read this news or not.
		$sql2 	= "SELECT * FROM sv_read_news_record WHERE user_id=$user_id AND news_id=$news_id";
		$result2 = $db->sql_query_limit($sql2, 1);
		if ($db->sql_fetchrow($result2))
			continue;		
		
		// For each corp, show up to 3 news.
		if ($corp_count['$corp_id'] > 3)
			continue;
			
		// check if the news is already listed
		if (in_array ($news_id, $news_listed))
			continue;
			
		$show_news 	= true;
		
		$title		= $row['title'];
		$link		= $row['link'];
		$snippet	= $row['snippet'];		
		
		$template->assign_block_vars('news', array(
				'TITLE'							=> $title,
				'LINK'							=> $link,
				'SNIPPET'						=> $snippet,				
				'USER_ID'						=> $user_id,
				'NEWS_ID'						=> $news_id,
				'RELATED_CORP_ID'				=> $corp_id,
			)
		);
		
		$news_listed[] = $news_id;
		++$i;
		if ($i >= $max)
			break;
			
		$corp_count['$corp_id'] += 1;		
	}
	
	$db->sql_freeresult($result);
		
	if ($i >= $max)
		return $show_news;
		
	// no enough news, get more.
	// Get popular news.
	// Select the read mostly news within 3 days. 
	$time_1_week_ago = get_taiwan_time() - 3 * 24 * 60 * 60;
	$sql 	= "SELECT news_id, COUNT(news_id) as cnt FROM sv_read_news_record WHERE time>$time_1_week_ago GROUP BY news_id  ORDER BY cnt DESC";
	$result = $db->sql_query_limit($sql, $max - $i);		
		
	while ($row = $db->sql_fetchrow($result))
	{
		$news_id	= $row['news_id'];			
		$cnt		= $row['cnt'];			
			
		// check if the user have read this news or not.
		$sql2 	= "SELECT * FROM sv_read_news_record WHERE user_id=$user_id AND news_id=$news_id";
		$result2 = $db->sql_query_limit($sql2, 1);
		if ($db->sql_fetchrow($result2))
			continue;
			
		// Get the news
		$sql2 	= "SELECT * FROM sv_news WHERE news_id=$news_id";
		$result2 = $db->sql_query_limit($sql2, 1);
		if (! ($row2 = $db->sql_fetchrow($result2)))
			continue;
			
		// check if the news is already listed
		if (in_array ($news_id, $news_listed))
			continue;

		$show_news 	= true;
			
		$title		= $row2['title'];
		$link		= $row2['link'];
		$snippet	= $row2['snippet'];		
			
		$template->assign_block_vars('news', array(
				'TITLE'							=> $title,
				'LINK'							=> $link,
				'SNIPPET'						=> $snippet,
				'USER_ID'						=> $user_id,
				'NEWS_ID'						=> $news_id,
				'NEWS_CNT'						=> $cnt,
				'RELATED_CORP_ID'				=> 'POPULAR NEWS',
			)
		);
		
		$news_listed[] = $news_id;
		++$i;
		if ($i >= $max)
			break;				
	}		

	$db->sql_freeresult($result);
	
	if ($i >= $max)
		return $show_news;
		
	// no enough news, get more.
	// Get news about the whole market (with corp id 0001). 
	$sql 	= "SELECT * FROM sv_news WHERE corp_id='0001' AND time > $news_after_this_time ORDER BY time DESC";
	$result = $db->sql_query_limit($sql, ($max - $i + 1) * 2);
	while ($row = $db->sql_fetchrow($result))
	{
		$news_id	= $row['news_id'];
		$corp_id	= $row['corp_id'];
		
		// check if the user have read this news or not.
		$sql2 	= "SELECT * FROM sv_read_news_record WHERE user_id=$user_id AND news_id=$news_id";
		$result2 = $db->sql_query_limit($sql2, 1);
		if ($db->sql_fetchrow($result2))
			continue;
		
		// check if the news is already listed
		if (in_array ($news_id, $news_listed))
			continue;
			
		$show_news 	= true;
		
		$title		= $row['title'];
		$link		= $row['link'];
		$snippet	= $row['snippet'];		
		
		$template->assign_block_vars('news', array(
				'TITLE'							=> $title,
				'LINK'							=> $link,
				'SNIPPET'						=> $snippet,				
				'USER_ID'						=> $user_id,
				'NEWS_ID'						=> $news_id,
				'RELATED_CORP_ID'				=> $corp_id,
			)
		);
		
		$news_listed[] = $news_id;
		++$i;
		if ($i >= $max)
			break;				
	}	
	
	$db->sql_freeresult($result);
	
	return $show_news;
}

// list brief history
function list_brief_history($query_user_id)
{
	global $db, $template;
	
	$sql2		= 'SELECT * FROM sv_user_value WHERE user_id=' . $query_user_id . ' ORDER BY date DESC';
	$result2 	= $db->sql_query_limit($sql2, 1);
	if (!($thisrow2 = $db->sql_fetchrow($result2)))
		return false;
		
	$user_value = $thisrow2['value'];
	if ($user_value == 0)
		return false;
	
	$show = false;
	$sql2		= 'SELECT * FROM sv_brief_history WHERE user_id=' . $query_user_id;
	$result2 	= $db->sql_query($sql2);
	while ($thisrow2 = $db->sql_fetchrow($result2))
	{
		$corp_id = $thisrow2['corp_id'];
		$share = $thisrow2['share'];
		$price = $thisrow2['price'];
		$cost = $thisrow2['cost'];
		$gain_or_loss = $thisrow2['gain_or_loss'];
		$deal_time = $thisrow2['deal_time'];
		$status = $thisrow2['status'];
		
		if ($deal_time == 0)
		{
			$template->assign_block_vars('bh_holding', array(
				'CORP_ID'					=> $corp_id,
				'CORP_NAME'					=> get_corp_chinese_name($corp_id),
				'SHARE'						=> $share,
				'UNIT'						=> (int)($share / TRANSACTION_UNIT),
				'PRICE'						=> round($price, 1),
				'COST'						=> round($cost, 1),
				'GAIN_OR_LOSS'				=> number_format(abs($gain_or_loss)),
				'GAIN'						=> ($gain_or_loss > 0),
				'PERCENT'					=> round(($gain_or_loss) * 100/$user_value, 1),
			)
		);
		}
		else if ($deal_time == 1)
		{
			$template->assign_block_vars('bh_shorting', array(
				'CORP_ID'					=> $corp_id,
				'CORP_NAME'					=> get_corp_chinese_name($corp_id),
				'SHARE'						=> $share,
				'UNIT'						=> (int)($share / TRANSACTION_UNIT),
				'PRICE'						=> round($price, 1),
				'COST'						=> round($cost, 1),
				'GAIN_OR_LOSS'				=> number_format(abs($gain_or_loss)),
				'GAIN'						=> ($gain_or_loss > 0),
				'PERCENT'					=> round(($gain_or_loss) * 100/$user_value, 1),
			)
		);
		}
		else
		{
			$template->assign_block_vars('bh_sold', array(
				'CORP_ID'					=> $corp_id,
				'CORP_NAME'					=> get_corp_chinese_name($corp_id),
				'SHARE'						=> $share,
				'UNIT'						=> (int)($share / TRANSACTION_UNIT),
				'PRICE'						=> round($price, 1),
				'COST'						=> round($cost, 1),
				'GAIN_OR_LOSS'				=> number_format(abs($gain_or_loss)),
				'GAIN'						=> ($gain_or_loss > 0),
				'PERCENT'					=> round(($gain_or_loss) * 100/$user_value, 1),
				'TIME'						=> $deal_time,
				'YEAR'						=> date('Y', $deal_time),
				'MONTH'						=> date('m', $deal_time),				
			)
		);
		}
		$show = true;
	}
	
	$db->sql_freeresult($result);		
	
	return $show;
}

// list hot corps on buy pages.
function list_hot_corp($max)
{
	global $db, $template;

	$hot_corp_list = false;
	
	$time_1_month_ago = get_taiwan_time() - 30 * 24 * 60 * 60;
	$sql 	= "SELECT corp_id, SUM(share*price) FROM sv_transaction where request_time > $time_1_month_ago GROUP BY corp_id  order by sum(share*price) desc";
	$result = $db->sql_query_limit($sql,$max); 
	$i = 0;
	while ($row = $db->sql_fetchrow($result))
	{
		if (is_valid_corp_id($row['corp_id']) && get_corp_chinese_name($row['corp_id']) != '')
		{
			$hot_corp_list = true;
		
			// Send vars to template
			$template->assign_block_vars('hot_corp_list', array(
				'CORP_ID'						=> $row['corp_id'],
				'CORP_NAME'						=> get_corp_chinese_name($row['corp_id']),
				'INDEX'							=> $i,
				)
			);
			
			$i = $i + 1;
		}
	}
	
	$db->sql_freeresult($result);
	
	return $hot_corp_list;
}

// list the corps in which the user may be interested .
function list_corps_may_interest($user_id, $max)
{
	global $db, $template;
	
	$corp = get_user_interested_corp($user_id, 10);
	
	if (sizeof($corp) == 0)
		return false;
		
	$corps_may_interest_list = false;	
	$i = 0;
	
	foreach($corp as $c)
	{
		if (is_valid_corp_id($c) && get_corp_chinese_name($c) != '')
		{
			$corps_may_interest_list = true;
		
			// Send vars to template
			$template->assign_block_vars('corps_may_interest_list', array(
				'CORP_ID'						=> $c,
				'CORP_NAME'						=> get_corp_chinese_name($c),
				'INDEX'							=> $i,
				)
			);
			
			$i = $i + 1;
		}		
	}
	
	return $corps_may_interest_list;
}

// list user roi on performance and query user page.
function list_user_roi($user_id)
{
	global $db, $template;

	$show_1_month_roi = false;
	$show_3_month_roi = false;
	$show_6_month_roi = false;
	$show_12_month_roi = false;

	$sql	= 'SELECT roi, period FROM sv_user_roi WHERE user_id=' . $user_id;
	$result = $db->sql_query($sql); 
	while ($row = $db->sql_fetchrow($result))
	{
		switch($row['period'])
		{
			case 30:
				$show_1_month_roi = true;
				$roi_1_month = round($row['roi']*100, 1);		
			break;
			
			case 90:
				$show_3_month_roi = true;
				$roi_3_month = round($row['roi']*100, 1);		
			break;
			
			case 180:
				$show_6_month_roi = true;
				$roi_6_month = round($row['roi']*100, 1);		
			break;
			
			case 360:
				$show_12_month_roi = true;
				$roi_12_month = round($row['roi']*100, 1);		
			break;
			
			default:
			break;
		}	
	}
	
	$db->sql_freeresult($result);
	
	$date = get_latest_date_for_ranking();
	
	$sql	= 'SELECT band, roi, period FROM sv_whole_site_roi where date="' . $date . '"';
	$result = $db->sql_query($sql); 
	while ($row = $db->sql_fetchrow($result))
	{
			
		switch($row['period'])
		{
			case 30:
				if ($row['band'] == 0)
				{
					$roi_1_month_TAIEX = round($row['roi']*100, 1);					
				}
				else if ($row['band'] == 20)
				{
					$roi_1_month_band_20 = round($row['roi']*100, 1);					
				}
				else if ($row['band'] == 50)
				{
					$roi_1_month_band_50 = round($row['roi']*100, 1);					
				}
				else if ($row['band'] == 100)
				{
					$roi_1_month_band_100 = round($row['roi']*100, 1);					
				}
				
			break;
			
			case 90:
				
				if ($row['band'] == 0)
				{
					$roi_3_month_TAIEX = round($row['roi']*100, 1);					
				}
				else if ($row['band'] == 20)
				{
					$roi_3_month_band_20 = round($row['roi']*100, 1);					
				}
				else if ($row['band'] == 50)
				{
					$roi_3_month_band_50 = round($row['roi']*100, 1);					
				}
				else if ($row['band'] == 100)
				{
					$roi_3_month_band_100 = round($row['roi']*100, 1);					
				}
				
			break;
			
			case 180:
				
				if ($row['band'] == 0)
				{
					$roi_6_month_TAIEX = round($row['roi']*100, 1);					
				}
				else if ($row['band'] == 20)
				{
					$roi_6_month_band_20 = round($row['roi']*100, 1);					
				}
				else if ($row['band'] == 50)
				{
					$roi_6_month_band_50 = round($row['roi']*100, 1);					
				}
				else if ($row['band'] == 100)
				{
					$roi_6_month_band_100 = round($row['roi']*100, 1);					
				}
			break;
			
			case 360:
				
				if ($row['band'] == 0)
				{
					$roi_12_month_TAIEX = round($row['roi']*100, 1);					
				}
				else if ($row['band'] == 20)
				{
					$roi_12_month_band_20 = round($row['roi']*100, 1);					
				}
				else if ($row['band'] == 50)
				{
					$roi_12_month_band_50 = round($row['roi']*100, 1);					
				}
				else if ($row['band'] == 100)
				{
					$roi_12_month_band_100 = round($row['roi']*100, 1);					
				}
			break;
			
			default:
			break;
		}	
	}
	
	$db->sql_freeresult($result);
	
	$template->assign_vars(array(
		'SHOW_1_MONTH_ROI'	=>	$show_1_month_roi,
		'SHOW_3_MONTH_ROI'	=>	$show_3_month_roi,
		'SHOW_6_MONTH_ROI'	=>	$show_6_month_roi,
		'SHOW_12_MONTH_ROI'	=>	$show_12_month_roi,
		
		'S_ROI_1_MONTH'		=>	$roi_1_month,
		'S_ROI_3_MONTH'		=>	$roi_3_month,
		'S_ROI_6_MONTH'		=>	$roi_6_month,
		'S_ROI_12_MONTH'	=>	$roi_12_month,
		
		'S_ROI_1_MONTH_TAIEX'		=>	$roi_1_month_TAIEX,
		'S_ROI_3_MONTH_TAIEX'		=>	$roi_3_month_TAIEX,
		'S_ROI_6_MONTH_TAIEX'		=>	$roi_6_month_TAIEX,
		'S_ROI_12_MONTH_TAIEX'		=>	$roi_12_month_TAIEX,
		
		'S_ROI_1_MONTH_BAND_20'		=>	$roi_1_month_band_20,
		'S_ROI_3_MONTH_BAND_20'		=>	$roi_3_month_band_20,
		'S_ROI_6_MONTH_BAND_20'		=>	$roi_6_month_band_20,
		'S_ROI_12_MONTH_BAND_20'	=>	$roi_12_month_band_20,
		
		'S_ROI_1_MONTH_BAND_50'		=>	$roi_1_month_band_50,
		'S_ROI_3_MONTH_BAND_50'		=>	$roi_3_month_band_50,
		'S_ROI_6_MONTH_BAND_50'		=>	$roi_6_month_band_50,
		'S_ROI_12_MONTH_BAND_50'	=>	$roi_12_month_band_50,
		
		'S_ROI_1_MONTH_BAND_100'		=>	$roi_1_month_band_100,
		'S_ROI_3_MONTH_BAND_100'		=>	$roi_3_month_band_100,
		'S_ROI_6_MONTH_BAND_100'		=>	$roi_6_month_band_100,
		'S_ROI_12_MONTH_BAND_100'		=>	$roi_12_month_band_100,
		));
		
}

?>